/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.oai.metadataRepository.cli;

import cz.mzk.oai.metadataRepository.repository.Identifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 *
 * @author Martin Řehánek (rehan at mzk.cz)
 */
public class CollectionsItemsMapping {

    private final Map<String, List<Identifier>> collectionIdListMap = new HashMap<String, List<Identifier>>();
    private Document doc = null;

    public void addItem(Identifier id, String collectionName) {
        List<Identifier> idList = collectionIdListMap.get(collectionName);
        if (idList == null) {
            idList = new ArrayList<Identifier>();
            collectionIdListMap.put(collectionName, idList);
        }
        idList.add(id);
    }

    public List<Identifier> getItemsInCollection(String collectionName) {
        List<Identifier> idList = collectionIdListMap.get(collectionName);
        return idList == null ? Collections.<Identifier>emptyList() : idList;
    }

    public Document asXml() {
        if (this.doc == null) {
            this.doc = buildDocument();
        }
        return this.doc;
    }

    private Document buildDocument() {
        Document result = DocumentHelper.createDocument();
        Element root = result.addElement("collections");
        for (String collectionName : collectionIdListMap.keySet()) {
            Element collection = root.addElement("collection");
            collection.addAttribute("name", collectionName);
            for (Identifier id : collectionIdListMap.get(collectionName)) {
                Element item = collection.addElement("item");
                item.addText(id.toString());
            }
        }
        return result;
    }
}
